<template>
  <el-dialog title="上传文件" :visible.sync="uploadVisible" width="400px" center :append-to-body="true">
    <div>
      <el-upload
        class="upload-demo"
        :action="addNodeFileUrl1"
        :auto-upload="false"
        :http-request="uploadFunc"
        :on-change="handleChange"
        :limit="1"
        @closed='closeWindow'
        ref="upload"
        :file-list="theFileList"
        drag
        :on-exceed="outLimit"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          <span>
            将文件拖到此处，或
            <em>点击上传</em>
          </span>
        </div>
        <div class="el-upload__tip" slot="tip">
          <i class="fa fa-exclamation-circle" aria-hidden="true"></i>&nbsp;&nbsp;一次只能选择1个文件进行上传
        </div>
      </el-upload>
    </div>
    <div class="loading" v-show="loading">
      <el-progress type="line" :percentage="percentage" :text-show="true">
      </el-progress>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="stopDownload">取消上传</el-button>
      <el-button type="primary" @click="submitUpload" :disabled="openUpload||loading">开始上传</el-button>
    </div>
  </el-dialog>
</template>
<script>
import axios from "axios";
import { mapState } from 'vuex';
// var ls = require("pull-file-reader");
// var ipfsClient = require("ipfs-http-client");
// var pull = require("pull-stream");
// var fr = new FileReader();
export default {
  name: "UploadFile",
  props: ["currFileId", 'nodeData'],
  data() {
    return {
      addNodeFileUrl1: "",
      source:null,
      // loading: false,
      // percentage: 0,
      openUpload: false,
      uploadFileList: 0,
      uploadVisible: false,
      uploadLoading: false,
      network: 0,
      theFileList:[],
    };
  },
  created(){
    console.log(this.$store.state.uploadLoading)
    if(this.$store.state.uploadLoading==true){
      this.theFileList=this.$store.state.uploadList;
      console.log(this.theFileList)
    }else{
      this.$store.commit('setUploadList',[]);
    }
  },
  watch: {
    uploadVisible: function(newVal, oldVal) {
      if (newVal == true) {
        if (this.$refs.upload !== undefined) {
          // this.$refs.upload.clearFiles();
        }
        this.uploadFileList = 0;
      }else{
        if(this.$store.state.uploadLoading==true){
          this.$message.warning('上传工作将在后台继续');
        }
        // this.loading=false;
      }
    }
  },
  computed:mapState({
    loading:state=>state.uploadLoading,
    percentage:state=>state.uploadPercent,
  }),
  methods: {
    // uploadFunc(e) {
    //   console.log(this.$store.state.ipfsArray);
    //   console.log(this.upFileList[0]);
    //   console.log(e.file);
    //   let _this = this;
    //   // let fileTemp = [];
    //   // fileTemp.push({
    //   //   path: e.file.name,
    //   //   content: ls(e.file,[])
    //   // });
    //   let ipfsPort = this.$store.state.ipfsArray[0];
    //   if (ipfsPort == []) {
    //     _this.$message.error("获取节点失败");
    //   } else {
    //     _this.loading = true;
    //     pull(
    //       ls(e.file),
    //       pull.collect(function(err, buffs) {
    //         var contents = Buffer.concat(buffs);
    //         ipfsPort.add(contents).then(
    //           res => {
    //             _this.loading = false;
    //             console.log(res);
    //             (_this.network = 0), _this.insertFile(res[0]);
    //             _this.uploadVisible = false;
    //           },
    //           err => {
    //             console.log(err);
    //             _this.$message.error("网络异常");
    //           }
    //         );
    //       })
    //     );
    //     const fileTemp = ls(e.file);
    //   }
    // },
    // handleChange1(file, fileList) {
    //   this.upFileList = [];
    //   console.log(file);
    //   console.log(fileList);
    //   console.log(this.inIpfs);
    //   console.log(this.outIpfs);
    //   this.upFileList = fileList;
    // },
    stopDownload(){
      this.source.cancel('用户取消上传');
      this.$message.info('取消上传');
      this.$store.commit('setUploadList',[]);
      this.$store.commit('setUploadLoading',false)
      this.$store.commit('setUploadPercent',0);
      this.uploadVisible=false;
    },
    outLimit(){
      this.$message.error('当前不支持多文件同时上传');
    },
    closeWindow(){
      this.loading=false;
      this.$message.warning('上传工作将在后台继续');
    },
    uploadFunc(e) {
      console.log('uploadFunc addNodeFileUrl', this.$store.state.ipfsArray);
      console.log('uploadFunc>>', e);
      let formData = new FormData();
      formData.append("file", e.file);
      if(this.$store.state.ipfsArray==0){
        this.$message.error('获取请求路径失败,请检查网络或呼叫管理员');
      }else {
        this.$store.commit('setUploadLoading',true)
        this.source = axios.CancelToken.source();
          axios.post(this.$store.state.ipfsArray[0], formData, {
            onUploadProgress: progressEvent => {
                let complete = Math.round((progressEvent.loaded / progressEvent.total ).toFixed(2) * 100);
                this.$store.commit('setUploadPercent',complete);
                if(complete == 100) {
                }
            },
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            cancelToken:this.source.token,
        }).then(res => {
          console.log('========================', res);
          if (res.status === 200) {
            this.insertFile(res.data);
          }else {
            this.$store.commit('setUploadLoading',false)
            this.$message.warning('网络错误，上传失败');
          }
        },err => {
          this.$message({
            message: "操作失败：上传文件超时",
            type: "error"
          });
          this.uploadVisible = false;
          console.log(err);
        });
      }
    },
    handleChange(file, fileList) {
        this.uploadFileList=fileList.length;
        this.fileListTemp = fileList
        console.log(this.theFileList);
        if(file.raw.size=="0"&&file.raw.type==''){
          this.$message.error('当前不支持文件夹上传');
          this.theFileList=[];
        }else if(this.theFileList.length>2){
          this.$message.error('当前不支持多文件上传');
          this.theFileList=[];
        }else{
          this.$store.commit('setUploadList',this.fileListTemp)
        }
    },
    submitUpload() {
      if (this.upFileList == 0) {
        this.$message.error("未选择上传文件");
      } else {
        this.uploadLoading = true;
        this.$refs.upload.submit();
      }
    },
    insertFile(insert) {
      console.log(insert);
      console.log("insert state.fileObj", this.currFileId);
      let para = {
        netFrom: this.$store.state.ipfsArray[2],
        type: 0,
        hash: insert.Hash,
        size: insert.Size,
        name: insert.Name,
        dirId: this.currFileId == undefined ? localStorage.getItem("dirId") : this.currFileId
      };
      console.log(para);
      this.$http.post("/file/insert", para).then(res => {
        console.log(res);
        if (res.status == 200) {
          console.log(para.name + "上传成功...", this.currFileId);
          this.$store.commit('setUploadList',[]);
          this.$store.commit('setUploadLoading',false)
          this.$store.commit('setUploadPercent',0);
          this.uploadVisible = false;
          this.uploadLoading = false;
          this.$message({
            type: "success",
            message: para.name + "上传成功..."
          });
          this.$emit("clearSelsForDel", this.nodeData);
        } else {
          this.uploadLoading = false;
          this.$store.commit('setUploadLoading',false)
          this.$store.commit('setUploadPercent',0);
          this.$store.commit('setUploadList',[]);
          this.$message({
            type: "error",
            message: para.name + "上传失败..."
          });
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.loading {
  position: relative;
  bottom: 10px;
}
</style>
